﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Pheonix.CodeLibrary.Web;
using Pheonix.Fashionzoomer.Entity.SqlServer2000;
using Pheonix.CodeLibrary.Data;
using System.Collections.Generic;
using System.Text;
using Pheonix.CodeLibrary;
using Pheonix.Fashionzoomer.DAL;
using System.IO;

public partial class page_private_admin_shopdetail : AdminBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Title = SiteName + " - Shop Details [ Admin ]";
        if (!IsPostBack)
        {
            try
            {
                BindControls();

                if (Request.QueryString["id"] != null)
                {
                    int id = 0;
                    if (int.TryParse(Request.QueryString["id"], out id))
                        LoadEditData(id);
                }
            }
            catch (Exception ex)
            {
                uccResponseMessage.SetFailMessage("There was a problem in loading the page");
            }
        }
        if (Request.QueryString["id"] == null)
            lblTitle.Text = "Add a new shop";
        else
            lblTitle.Text = "Update shop";
    }

    private void BindControls()
    {
        lblShopCode.Text = "Auto generated - can be viewed after creating shop";

        CustomCollection<Shop> shops = Shop.GetAllShop();
        ddlMainBranch.DataSource = shops;
        ddlMainBranch.DataTextField = "ShopName";
        ddlMainBranch.DataValueField = "Id";
        ddlMainBranch.DataBind();

        lsbShopOwner.DataTextField = "UserName";
        lsbShopOwner.DataValueField = "Id";
        lsbShopOwner.DataSource = Pheonix.Fashionzoomer.Entity.SqlServer2000.User.GetAllUser();
        lsbShopOwner.DataBind();

        if(!IsPostBack)
            imgLogo.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/image/nologo.gif";
    }

    private string GenerateShopCode(int shopId)
    {
        StringBuilder shopCode = new StringBuilder("FZS");
        shopCode.Append(shopId.ToString().PadLeft(8,'0'));
        return shopCode.ToString().ToUpper();
    }

    private void LoadEditData(int editDataId)
    {
        Shop editShop = null;
        if (editDataId != 0)
            editShop = Shop.GetShopById(editDataId);
        if (editShop != null)
        {
            tbxShopName.Text = editShop.ShopName;
            lsbShopOwner.SelectedValue = editShop.ShopOwnerUserId.ToString();
            tbxBranchAddress.Text = editShop.BranchAddress;
            tbxEmail.Text = editShop.Email;
            tbxPhone.Text = editShop.Phone;
            lblShopCode.Text = editShop.ShopCode;
            ddlMainBranch.SelectedValue = editShop.MainBranchShopId.ToString();
            imgLogo.ImageUrl = editShop.ShopLogoPath;
            tbxCity.Text = editShop.City;
            tbxCountry.Text = editShop.Country;
            tbxKeywords.Text = editShop.Keywords;
            cbxFeatured.Checked = editShop.IsFeatured;
        }
    }

    private string UploadImage(string shopCode)
    {
        if (fluShopLogo.HasFile)
        {
            string imagePath = null;
            string tempImagePath = (string)(new AppSettingsReader().GetValue("TempPath", typeof(string)));
            string mimeType = fluShopLogo.PostedFile.ContentType;

            if (mimeType == "image/jpeg" || mimeType == "image/gif" || mimeType == "image/png")
            {
                string tempFileName = tempImagePath + Guid.NewGuid() +
                    Path.GetExtension(fluShopLogo.FileName);
                fluShopLogo.SaveAs(MapPath(tempFileName));

                imagePath = ShopManager.UploadShopImage(tempFileName, shopCode);
                return imagePath;
            }
            else
                uccResponseMessage.SetFailMessage("Only JPG, GIF, PNG image allowed");
        }
        return null;
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            int shopId = 0;
            Shop editShop = null;
            string shopOldName = string.Empty;

            if (Request.QueryString["id"] != null)
            {
                if (int.TryParse(Request.QueryString["id"], out shopId))
                {
                    editShop = Shop.GetShopById(shopId);
                    if(editShop != null)
                        shopOldName = editShop.ShopName;
                }
            }

            string shopName = Utility.FilterInputText(tbxShopName.Text);
            if (shopName == shopOldName || CustomCommand.IsShopNameFree(shopName))
            {
                int shopOwnerId = 0;
                if (int.TryParse(lsbShopOwner.SelectedValue, out shopOwnerId))
                {
                    string branchAddress = Utility.FilterInputText(tbxBranchAddress.Text);
                    string email = Utility.FilterInputText(tbxEmail.Text);
                    string phone = Utility.FilterInputText(tbxPhone.Text);
                    int mainBranch = -1;
                    if(ddlMainBranch.SelectedValue !=null)
                        int.TryParse(ddlMainBranch.SelectedValue, out mainBranch);
                    string city = Utility.FilterInputText(tbxCity.Text);
                    string country = Utility.FilterInputText(tbxCountry.Text);
                    bool featured = cbxFeatured.Checked;
                    string keywords = Utility.FilterInputText(tbxKeywords.Text);

                    if (editShop != null)
                    {
                        editShop.ShopName = shopName;
                        editShop.ShopOwnerUserId = shopOwnerId;
                        editShop.BranchAddress = branchAddress;
                        editShop.Email = email;
                        editShop.Phone = phone;
                        editShop.LastUpdate = DateTime.Now;
                        editShop.MainBranchShopId = mainBranch;
                        editShop.City = city;
                        editShop.Country = country;
                        editShop.IsFeatured = featured;
                        editShop.Keywords = keywords;
                        string newShopLogo = UploadImage(editShop.ShopCode);
                        if(!string.IsNullOrEmpty(newShopLogo))
                            editShop.ShopLogoPath = newShopLogo;

                        if (editShop.Save())
                        {
                            uccResponseMessage.SetSuccessMessage("Shop successfuly updated");
                            LoadEditData(shopId);
                        }
                        else
                            uccResponseMessage.SetFailMessage("Could not update shop");
                    }
                    else
                    {
                        string imagePath = "";
                        string shopCode = "";

                        int newShopId = Shop.CreateNewShop(shopName, imagePath, shopOwnerId, 0, 0, branchAddress, email, phone,
                            shopCode, 0, 0, 0, DateTime.Now, DateTime.Now, mainBranch,country, featured, keywords, city);

                        shopCode = GenerateShopCode(newShopId);
                        imagePath = UploadImage(shopCode);

                        bool updateSuccess = Shop.UpdateShop(newShopId, shopName, imagePath, shopOwnerId, 
                            0, 0, branchAddress, email, phone, shopCode, 0, 0, 0, DateTime.Now, DateTime.Now,
                            mainBranch, country, featured, keywords, city);

                        if (updateSuccess)
                        {
                            uccResponseMessage.SetSuccessMessage("Shop successfuly created");
                            LoadEditData(newShopId);
                        }
                        else
                            uccResponseMessage.SetFailMessage("Could not create shop");
                    }
                }
                else
                    uccResponseMessage.SetFailMessage("Username of shop owner is invalid");
            }
            else
                uccResponseMessage.SetFailMessage("Shop name is already taken");
        }
        else
            uccResponseMessage.SetFailMessage("Could not save because of invalid data");
    }

    protected void Back_Click(object sender, EventArgs e)
    {
        Response.Redirect("shoplist.aspx");
    }
}
